<script setup lang="ts">
import {ref, onMounted, computed, reactive} from 'vue';
import {Notification, Modal} from '@arco-design/web-vue';
import {invoke} from "@tauri-apps/api/core";
import {useRouter} from 'vue-router';
import {App} from '@/model/App.ts'
import {LocalStorage} from "@/utils/cache.ts";
import emitter from "@/bus/eventBus.ts";
import TarotIcon from "@/components/TarotIcon.vue";

import icons from 'virtual:svg-icons';
import {IconDelete} from "@arco-design/web-vue/es/icon";

// 获取路由
const router = useRouter();

// 定义应用列表
const apps = ref<Array<App>>([] as Array<App>);

// 模态框状态
const showModal = ref(false);
// 定义隐藏ID
const idHidden = ref(false);

// 定义表单类型
const formOption = ref(false);
const formData = reactive<App>(new App('', '', '', 'shumajiadian', '暂无', false));

// 定义搜索关键字
const searchKey = ref('');
// 定义状态
const loading = ref(false);


/**
 * @description 计算属性：过滤后的charts列表
 * @param       apps    源数据
 * @returns             过滤后的数据
 */
const filteredApps = computed(() => {
  if (!searchKey.value.trim()) {
    return apps.value;
  }
  const keyword = searchKey.value.toLowerCase();
  return apps.value.filter(app =>
      app.name.toLowerCase().includes(keyword)
  );
});

/**
 * @description 搜索处理方法
 * @param value 搜索关键字
 */
const handleSearch = (value: string) => {
  searchKey.value = value;
};

/**
 * @function handleSubmit
 * @description 添加应用
 * @author xincan
 * @date 2025-11-07
 */
const handleSubmit = async () => {
  let msg = "添加"
  if (formOption.value) {
    msg = "编辑"
  }

  Modal.confirm({
    title: msg + '应用',
    content: '确定要'+msg+'该应用吗？',
    onOk: async () => {

      try {
        if (formData.id === '' && !formOption.value) {
          const app: App = await invoke<App>("add_app", {name: formData.name, url: formData.url, icon: formData.icon, description: formData.description});
          apps.value.push(app);
        }else{
          const app: App = await invoke<App>("edit_app", {app: formData});
          // 根据id进行更新
          apps.value = apps.value.map(item => item.id === app.id ? app : item);
          await updateCache('edit', formData as App)
        }
        Notification.success({content: msg+'应用成功'});
      }catch (err) {
        console.error(err);
        if (formData.id === '' && !formOption.value) {
          Notification.error({content: msg + '应用失败'});
        } else {
          Notification.error({content: msg + '应用失败'});
        }
      }
      showModal.value = false;
    },
    onCancel: () => {
      Notification.warning({content: '取消'+msg+'应用'});
    },
  });
};

/**
 * @function resetForm
 * @description 重置表单
 * @author xincan
 * @date 2025-11-07
 */
const resetForm = () => {
  showModal.value = false;
  Object.assign(formData, new App('', '', '', 'shumajiadian', '暂无', false))
};

/**
 * @function handleAdd
 * @description 添加应用
 * @author xincan
 * @date 2025-11-07
 */
const handleAdd = () => {
  formOption.value = false;
  showModal.value = true;
  Object.assign(formData, new App('', '', '', 'shumajiadian', '暂无', false))
  // handleClick()
};

/**
 * @function handleDelete
 * @description 编辑应用
 * @author xincan
 * @date 2025-11-07
 * @param app 应用信息
 */
const handleEdit = async (app: App) => {
  formOption.value = true;
  Object.assign(formData, app)
  showModal.value = true;
  // handleClick()
};

/**
 * @function handleDelete
 * @description 删除应用
 * @author xincan
 * @date 2025-11-07
 * @param appId 应用ID
 */
const handleDelete = async (appId: string) => {
    try {
      // 删除应用
      await invoke<App>("delete_app", {id: appId});
      // 从列表中删除
      const delApp: App = new App('', '', '','shumajiadian', '暂无',false);
      for (let i = 0; i < apps.value.length; i++) {
        if (apps.value[i].id === appId) {
          Object.assign(delApp, apps.value[i] as App);
          apps.value.splice(i, 1);
          break;
        }
      }
      // 同步删除Header中的应用
      await updateCache('delete', delApp)
      Notification.success({content: '应用删除成功'});
    } catch (err) {
      console.error(err);
      Notification.error({content: '删除应用失败'});
    }
};

/**
 * @function handleAppSelect
 * @description 应用选择, 添加到Header中, 跳转到应用对应的charts列表详情页
 * @author xincan
 * @date 2025-11-07
 */
const handleAppSelect = (app: App) => {
  // 更新缓存
  updateCache('select', app)
  // 跳转到应用对应的charts列表详情页
  router.replace({name: 'Repos', query: {appId: app.id}});
};

/**
 * @function updateCache
 * @description 更新缓存
 * @param option 操作类型
 * @param app 应用信息
 */
const updateCache = async (option: string, app: App) => {
  // 更新缓存
  const store = new LocalStorage(option, app).updateCache()
  // 发送事件, 更新Header中选中的应用
  emitter.emit('apps-header', store);
};

/**
 * @function switchIcon
 * @description 切换图标
 * @param name 图标名称
 */
const switchIcon = (name: string) => {
  // 去除选中图标的active样式, 给当前点击的图标添加active样式
  document.querySelectorAll('.tarot-icon-list > .tarot-icon').forEach(item => {
    item.classList.remove('active')
    if (item.getAttribute('name') === name) {
      item.classList.add('active')
    }
  })
  formData.icon = name
};


/**
 * @function onMounted
 * @description 组件挂载时加载应用列表
 * @author xincan
 * @date 2025-11-07
 */
onMounted(async () => {
  try {
    apps.value = await invoke<Array<App>>("get_apps");
  } catch (err) {
    console.error(err);
    Notification.error({content: '加载应用失败'});
  }
});
</script>

<template>
  <div class="container">

    <div class="panel" id="app-container">
      <!-- 头部搜索 -->
      <div class="panel-header">
        <a-space>
          <a-input-search v-model="searchKey" placeholder="搜索应用" allow-clear :loading="loading" @search="handleSearch" style="width: 300px"/>
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-plus/>
            </template>
            添加应用
          </a-button>
        </a-space>
      </div>

      <!-- 应用列表 -->
      <div class="panel-content" >
        <a-row :gutter="8" v-if="apps.length" justify="start">
          <a-col v-for="app in filteredApps" :key="app.id" :span="4" :xs="24" :sm="12" :md="8" :lg="6">
            <a-card :title="app.name" @click="handleAppSelect(app as App)">
              <template #extra>

                <a-space @click.stop>
                  <a-tooltip content="编辑" mini>
                    <a-button type="text" size="mini" class="edit-btn" @click.stop="handleEdit(app as App)">
                      <template #icon>
                        <icon-edit/>
                      </template>
                    </a-button>

                  </a-tooltip>
                  <a-tooltip content="删除" mini>
<!--                    <a-button type="text" size="mini" class="delete-btn" @click.stop="handleDelete(app.id)">-->
<!--                      <template #icon>-->
<!--                        <icon-delete/>-->
<!--                      </template>-->
<!--                    </a-button>-->

                    <a-popconfirm content="确定要删除当前应用吗？" @ok="handleDelete(app.id)" position="br">
                      <a-button type="text" size="mini" class="delete-btn">
                        <icon-delete />
                      </a-button>
                    </a-popconfirm>

                  </a-tooltip>
                </a-space>

              </template>
              <div class="card-container">
                <tarot-icon :name="app.icon" size="40"  />
                <div class="card-content">
                  <span>应用地址</span>
                  <div>{{ app.url }}</div>
                  <span>应用说明</span>
                  <div>{{ app.description }}</div>
                </div>
              </div>

            </a-card>
          </a-col>
        </a-row>
        <a-empty v-else description="暂无应用"/>
      </div>
    </div>

    <!-- 编辑应用 -->
    <a-drawer popup-container="#app-container" :width="500" :visible="showModal" @ok="handleSubmit" @cancel="resetForm">

      <template #title>
        <icon-plus v-if="!formOption" />
        <icon-edit v-else />
        {{!formOption ?' 添加应用' : '编辑应用'}}
      </template>
      <a-form :model="formData">
        <a-form-item label="应用ID" field="id" v-show="idHidden">
          <a-input v-model="formData.id"/>
        </a-form-item>
        <a-form-item label="应用名称" field="name" :rules="[{ required: true, message: '请输入应用名称' }]">
          <a-input v-model="formData.name"/>
        </a-form-item>
        <a-form-item label="应用地址" field="url" :rules="[{ required: true, message: '请输入应用地址' }]">
          <a-input v-model="formData.url"/>
        </a-form-item>
        <a-form-item label="应用描述" field="description" :rules="[{ required: true, message: '请输入应用描述' }]">
          <a-textarea v-model="formData.description"/>
        </a-form-item>
        <a-form-item label="应用图标" field="icon" :rules="[{ required: true, message: '请选择应用图标' }]">
          <input type="hidden" v-model="formData.icon">
          <tarot-icon :name="formData.icon" size="32" />
        </a-form-item>
        <div>

          <div class="tarot-icon-list">
            <tarot-icon v-for="name in icons" :name="name" size="40" @icon-click="switchIcon" />
          </div>
        </div>
      </a-form>
    </a-drawer>

  </div>
</template>

<style lang="scss" scoped>
.container {
  display: flex;
  height: calc(100vh - 48px); // 减去顶部导航栏高度
  box-sizing: border-box;
}

.panel {
  flex: 1;
  height: 100%;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

// 调整头部样式
.panel-header {
  display: flex;
  padding: 8px;
  border-bottom: 1px solid var(--theme-bg-light);

  .arco-space {
    flex: 1;
    justify-content: start;
  }

  .arco-space-horizontal .arco-space-item {
    width: 100% !important;
  }

  .arco-input-search {
    width: 100% !important;
    color: var(--color-white) !important;
    background-color: var(--theme-bg-light) !important;

    :deep(.arco-icon) {
      color: var(--theme-primary);
    }

    :deep(.arco-icon-hover:hover::before) {
      background-color: var(--theme-bg-light) !important;
    }
  }

}

.panel-content {
  flex: 1;
  padding: 8px;
  color: var(--color-text-2);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */

  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }

  .empty-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--color-text-3);
    gap: 8px;

    .arco-icon {
      font-size: 24px;
    }
  }

  :deep(.arco-empty) {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0;
    color: var(--color-text-3);

    .arco-empty-image {
      width: 80px;
    }
  }

}

// 添加卡片样式
.arco-card {
  margin-bottom: 8px;
  transition: box-shadow 0.2s;
  background-color: var(--theme-bg-light);
  border: none;

  :deep(.arco-card-header) {
    padding: 8px;
    border-bottom: 1px solid var(--theme-primary);

    .arco-card-header-title {
      color: var(--theme-primary);
    }

    .arco-btn {
      background-color: var(--theme-bg);
      width: 28px;
      padding: 0;
    }

    .edit-btn, .delete-btn {
      color: var(--theme-primary);
      font-size: 18px;

      &:hover {
        color: white;
        background-color: var(--theme-primary) !important;
      }
    }
  }

  :deep(.arco-card-body) {
    padding: 8px;
    color: var(--color-text-4) !important;

    .card-container {
      display: flex;
      & > .tarot-icon {
        width: 100%;
        margin: 2%;
      }
      & > .card-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-content: flex-start;
        padding-left: 8px;
        gap: 8px;
      }

      & > .card-content > div:last-child {
        height: 40px;
        overflow-y: auto;
      }
    }
  }


  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    cursor: pointer;
  }
}

.tarot-icon-list {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  justify-content: flex-start; /* 左对齐 */
  align-content: flex-start;
  gap: 5px;
  background-color: var(--theme-bg-light);
  border-radius: 3px;
  overflow-y: auto; /* 超出时滚动 */
  margin-left: 24px;
  padding: 8px 8px 8px 20px;
  height: 150px;

  & > svg {
    padding: 3px;
    border: 1px solid var(--theme-bg-light);

  }

  & > svg:hover, & > svg.active {
    content: '';
    width: 100%;
    height: 100%;
    border: 1px solid var(--theme-primary);
    border-radius: 8px;
    padding: 3px;
  }
}
</style>